package com.atguigu.tingshu.search.listener;

import co.elastic.clients.elasticsearch.ElasticsearchClient;
import co.elastic.clients.elasticsearch.core.SearchRequest;
import co.elastic.clients.elasticsearch.core.search.HitsMetadata;
import com.alibaba.fastjson.JSON;
import com.atguigu.tingshu.common.constant.RabbitConstant;
import com.atguigu.tingshu.model.album.AlbumInfoSyncData;
import com.atguigu.tingshu.model.search.AlbumInfoIndex;
import com.atguigu.tingshu.search.repository.AlbumIndexRepository;
import com.atguigu.tingshu.search.service.SearchService;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.elasticsearch.repository.ElasticsearchRepository;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

@Component
@Slf4j
public class SearchReceiver {

    @Autowired
    private SearchService searchService;
    @Autowired
    private AlbumIndexRepository albumIndexRepository;
    @Autowired
    private ElasticsearchClient elasticsearchClient;

    @RabbitListener(queues = RabbitConstant.SEARCH_UPPER_QUEUE)
    public void upperQueue(String albumId){
        if (!StringUtils.isEmpty(albumId)){
            searchService.upperAlbum(Long.parseLong(albumId));
            log.info("专辑上架成功,id:"+albumId);
        }
    }

    @RabbitListener(queues = RabbitConstant.SEARCH_LOWER_QUEUE)
    public void lowerQueue(String albumId){
        if (!StringUtils.isEmpty(albumId)){
            searchService.lowerAlbum(Long.parseLong(albumId));
            log.info("专辑下架成功,id:"+albumId);
        }
    }

    @RabbitListener(bindings = @QueueBinding(value = @Queue(value = RabbitConstant.ALBUM_STAT_QUEUE, durable = "true"),
            exchange = @Exchange(value = RabbitConstant.SEARCH_EXCHANGE),
            key = RabbitConstant.UPDATE_ALBUM_STAT_ROUTING
    ))
    public void updateAlbumStat(String albumInfoSyncDataJson){
        AlbumInfoSyncData albumInfoSyncData = JSON.parseObject(albumInfoSyncDataJson, AlbumInfoSyncData.class);
        AlbumInfoIndex albumInfoIndex = albumIndexRepository.findById(Long.parseLong(albumInfoSyncData.getAlbumId())).get();

        String statType = albumInfoSyncData.getStatType();
        switch (statType){
            case "0401":
                albumInfoIndex.setPlayStatNum(Integer.valueOf(albumInfoSyncData.getStatNum()));
                break;
            case "0402":
                albumInfoIndex.setSubscribeStatNum(Integer.valueOf(albumInfoSyncData.getStatNum()));
                break;
            case "0403":
                albumInfoIndex.setBuyStatNum(Integer.valueOf(albumInfoSyncData.getStatNum()));
                break;
            case "0404":
                albumInfoIndex.setCommentStatNum(Integer.valueOf(albumInfoSyncData.getStatNum()));
                break;
        }
        Double hotScore = (double) (albumInfoIndex.getPlayStatNum() + 2 * albumInfoIndex.getSubscribeStatNum() + 3 * albumInfoIndex.getBuyStatNum() + 4 * albumInfoIndex.getCommentStatNum());
        albumInfoIndex.setHotScore(hotScore);

        //保存es
        albumIndexRepository.save(albumInfoIndex);

    }

    @RabbitListener(bindings = @QueueBinding(value = @Queue(value = RabbitConstant.UPDATEUSER_NICKNAME_QUEUE, durable = "true"),
            exchange =@Exchange(value = RabbitConstant.SEARCH_EXCHANGE),
            key = RabbitConstant.UPDATE_USER_NICKNAME_ROUTING
    ))
    @SneakyThrows
    public void updateUserNickName(String nickName){
        SearchRequest searchRequest = new SearchRequest.Builder()
                .index("albuminfo")
                .query(builder -> builder.match(builder1 -> builder1.field("announcerName.keyword").query(nickName)))
                .build();
        HitsMetadata<AlbumInfoIndex> hits = elasticsearchClient.search(searchRequest, AlbumInfoIndex.class).hits();
        hits.hits().forEach(hit -> {
            AlbumInfoIndex albumInfoIndex = hit.source();
            albumInfoIndex.setAnnouncerName(nickName);
            albumIndexRepository.save(albumInfoIndex);
        });
        log.info("更新用户昵称成功");
    }
}
